﻿using System;
using System.Windows;
using Pfz.Factoring;

namespace Pfz.WpfControls
{
	/// <summary>
	/// The heart of Pfz.WpfControls and Pfz.Databasing.WpfControls.
	/// This factory allows you to register IValueContainer controls, so
	/// whenever you need a control for a specific type, the right control
	/// will be created.
	/// </summary>
	public static class ControlFactory
	{
		/// <summary>
		/// Tries to create a control for the given data-type.
		/// The result can be null if there is not a control appropriate for the
		/// data-type.
		/// </summary>
		public static UIElement TryCreateFor(Type dataType)
		{
			var factory = Factories<IValueControl>.TryCreateFactory(dataType);

			if (factory == null)
				return null;

			return (UIElement)factory.Create();
		}
		
		/// <summary>
		/// Tries to create a control for the given data-type using the given
		/// displayName. If the control does not support displayName, a 
		/// LabellerControl will be created for it.
		/// The result can be null if there is no editor for the given data-type.
		/// </summary>
		public static UIElement TryCreateFor(Type dataType, string displayName)
		{
			if (dataType == null)
				throw new ArgumentNullException("dataType");
				
			UIElement result = (UIElement)TryCreateFor(dataType);
			
			if (result == null)
				return null;
			
			if (displayName != null)
			{
				IHasDisplayName hasDisplayName = result as IHasDisplayName;
				if(hasDisplayName != null)
					hasDisplayName.DisplayName = displayName;
				else
					result = new LabellerControl { Content = result, Label = displayName };
			}
			
			return result;
		}
	}
}
